<template>
  <el-dialog v-model="visible" title="添加好友" width="450px" :close-on-click-modal="false" @close="handleClose">
    <div class="add-friend-dialog">
      <el-form :model="addFriendForm" label-width="80px">
        <el-form-item label="微信号">
          <el-input v-model="addFriendForm.key" placeholder="请输入微信号或手机号" clearable @keyup.enter="handleSearchFriend"> </el-input>
        </el-form-item>

        <!-- 搜索结果 -->
        <div v-if="searchResult && searchResult.nick_name" class="search-result">
          <div class="user-info">
            <el-avatar :size="48" :src="searchResult.avatar_url" class="user-avatar">
              <img :src="avatar" />
            </el-avatar>
            <div class="user-detail">
              <div class="user-name">
                {{ searchResult.nick_name }}
                <el-icon v-if="searchResult.gender === 1" class="gender-icon male"><Male /></el-icon>
                <el-icon v-else-if="searchResult.gender === 2" class="gender-icon female"><Female /></el-icon>
              </div>
              <div class="user-location" v-if="searchResult.province || searchResult.city">地区：{{ searchResult.province }} {{ searchResult.city }}</div>
              <div class="user-status" v-if="searchResult.wx_account">
                <el-tag type="info" size="small">已是好友</el-tag>
              </div>
            </div>
          </div>
        </div>

        <!-- 验证信息输入框，按钮在下方右侧 -->
        <el-form-item label="验证信息" v-if="searchResult && searchResult.nick_name && !searchResult.wx_account">
          <el-input v-model="addFriendForm.msg" type="textarea" placeholder="请输入验证信息" :rows="3" />
          <div style="display: flex; justify-content: flex-end; margin-top: 6px">
            <el-button type="info" plain size="small" @click="showPresetDialog = true" style="border-radius: 16px">
              <el-icon style="margin-right: 4px"><Document /></el-icon>
              插入预设消息
            </el-button>
          </div>
        </el-form-item>

        <!-- 预设消息弹窗 -->
        <el-dialog v-model="showPresetDialog" title="选择预设消息" width="500px" @close="closePresetDialog">
          <div class="preset-dialog-header">
            <el-input
              v-model="presetFilter"
              placeholder="输入关键词筛选"
              size="small"
              style="width: 240px; margin-right: 12px"
              @keyup.enter="fetchPresetMessages"
            />
            <el-button type="primary" size="small" @click="fetchPresetMessages" :loading="loadingPresetMessages">搜索</el-button>
          </div>
          <div class="preset-card-list">
            <template v-if="presetMessages.length">
              <div
                v-for="msg in presetMessages"
                :key="msg.id"
                class="preset-card-item"
                :class="{ 'is-selected': selectedPresetMsg && selectedPresetMsg.id === msg.id }"
                @click="selectPresetRow(msg)"
                :title="msg.message"
              >
                <div
                  class="msg-content"
                  :class="{ expanded: hoveredCardId === msg.id }"
                  @mouseenter="hoveredCardId = msg.id"
                  @mouseleave="hoveredCardId = null"
                >
                  {{ msg.message }}
                </div>
                <span v-if="selectedPresetMsg && selectedPresetMsg.id === msg.id" class="selected-icon">✔</span>
              </div>
            </template>
            <div v-else class="no-preset-messages-card">暂无匹配的预设消息</div>
          </div>
          <div class="preset-dialog-footer">
            <el-pagination
              background
              layout="prev, pager, next, total"
              :current-page="presetPage.current"
              :page-size="presetPage.size"
              :total="presetPage.total"
              @current-change="handlePresetPageChange"
              small
            />
          </div>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="showPresetDialog = false">取消</el-button>
              <el-button type="primary" :disabled="!selectedPresetMsg" @click="confirmPresetMsg">确定</el-button>
            </span>
          </template>
        </el-dialog>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <template v-if="!searchResult || !searchResult.nick_name">
          <el-button type="primary" @click="handleSearchFriend" :loading="searching">下一步</el-button>
        </template>
        <template v-else-if="!searchResult.wx_account">
          <el-button type="primary" @click="handleAddFriend" :loading="addingFriend">发送请求</el-button>
        </template>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, watch, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import avatar from '@/assets/avatar.jpg';
import { seleteWechatStranger, addWechatStranger } from '@/api/wechat';
import { getAuthenticationList } from '@/api/userRate/friendVerify';
import { Male, Female, Document } from '@element-plus/icons-vue';

const props = defineProps({
  modelValue: Boolean,
  wxId: String
});
const emit = defineEmits(['update:modelValue', 'success']);

const visible = ref(props.modelValue);
watch(
  () => props.modelValue,
  (v) => (visible.value = v)
);
watch(visible, (v) => emit('update:modelValue', v));

const addFriendForm = ref({ key: '', msg: '' });
const searchResult = ref<any>(null);
const searching = ref(false);
const addingFriend = ref(false);
const presetMessages = ref<any[]>([]);
const loadingPresetMessages = ref(false);
const presetFilter = ref('');
const showPresetDialog = ref(false);
const selectedPresetMsg = ref<any>(null);
const presetPage = reactive({ current: 1, size: 8, total: 0 });
const hoveredCardId = ref<number | null>(null);

const fetchPresetMessages = async () => {
  if (!props.wxId) return;
  loadingPresetMessages.value = true;
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
    const params = { account: userInfo.username || '', current: presetPage.current, size: presetPage.size };
    const res = await getAuthenticationList(params);
    presetMessages.value = res.data?.records || [];
    presetPage.total = res.data?.total || 0;
  } catch {
    presetMessages.value = [];
  } finally {
    loadingPresetMessages.value = false;
  }
};
const selectPresetRow = (row: any) => {
  selectedPresetMsg.value = row;
};
const handlePresetPageChange = (page: number) => {
  presetPage.current = page;
  fetchPresetMessages();
};
const closePresetDialog = () => {
  selectedPresetMsg.value = null;
};
const confirmPresetMsg = () => {
  if (selectedPresetMsg.value) {
    addFriendForm.value.msg = selectedPresetMsg.value.message;
    showPresetDialog.value = false;
  }
};

const handleSearchFriend = async () => {
  if (!addFriendForm.value.key) {
    ElMessage.warning('请输入微信号或手机号');
    return;
  }
  if (!props.wxId) {
    ElMessage.warning('请先登录微信账号');
    return;
  }
  try {
    searching.value = true;
    const res = await seleteWechatStranger({ wxId: props.wxId, key: addFriendForm.value.key });
    if (res.data?.data && res.data.data.nick_name) {
      searchResult.value = res.data.data;
      if (searchResult.value.wx_account) ElMessage.info('该用户已经是您的好友');
      await fetchPresetMessages();
    } else {
      ElMessage.warning('未找到用户，请重新搜索');
      searchResult.value = null;
    }
  } catch {
    ElMessage.error('搜索好友失败');
    searchResult.value = null;
  } finally {
    searching.value = false;
  }
};
const handleAddFriend = async () => {
  if (!searchResult.value) {
    ElMessage.warning('请先搜索好友');
    return;
  }
  if (searchResult.value.wx_account) {
    ElMessage.warning('该用户已经是您的好友');
    return;
  }
  if (!props.wxId) {
    ElMessage.warning('请先登录微信账号');
    return;
  }
  try {
    addingFriend.value = true;
    const res = await addWechatStranger({ ...searchResult.value, wxId: props.wxId, msg: addFriendForm.value.msg, v3: searchResult.value.v3 });
    if (res.code === 200) {
      ElMessage.success('好友请求已发送');
      emit('success');
      handleClose();
    } else {
      ElMessage.error(res.msg || '添加好友失败');
    }
  } catch {
    ElMessage.error('添加好友失败');
  } finally {
    addingFriend.value = false;
  }
};
const handleClose = () => {
  visible.value = false;
  searchResult.value = null;
  addFriendForm.value = { key: '', msg: '' };
  presetMessages.value = [];
};
watch(
  () => addFriendForm.value.key,
  (v) => {
    if (!v) searchResult.value = null;
  }
);
</script>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
  name: 'AddFriendDialog',
  components: { Male, Female }
});
</script>
<style scoped lang="scss">
.add-friend-dialog {
  // background: linear-gradient(135deg, #f5f7fa 80%, #e3eaf6 100%);
  border-radius: 18px;
  // box-shadow: 0 8px 32px rgba(64, 158, 255, 0.08), 0 1.5px 8px rgba(0, 0, 0, 0.04);
  padding: 15px;
  .el-form-item {
    margin-bottom: 22px;
    .el-input,
    .el-textarea {
      border-radius: 8px;
      background: #fff;
      box-shadow: 0 1px 4px rgba(64, 158, 255, 0.04);
      transition: box-shadow 0.2s;
      &:focus-within {
        box-shadow: 0 2px 8px rgba(64, 158, 255, 0.12);
      }
    }
  }
  .search-result {
    margin: 18px 0;
    padding: 18px 20px;
    background: linear-gradient(120deg, #f5f7fa 80%, #e3eaf6 100%);
    border-radius: 14px;
    border: 1.5px solid #b3d8fd;
    box-shadow: 0 2px 12px rgba(64, 158, 255, 0.07);
    transition: box-shadow 0.2s;
    &:hover {
      box-shadow: 0 4px 24px rgba(64, 158, 255, 0.13);
    }
    .user-info {
      display: flex;
      align-items: flex-start;
      gap: 16px;
      .user-avatar {
        flex-shrink: 0;
        border-radius: 50%;
        box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
        border: 2px solid #e3eaf6;
      }
      .user-detail {
        flex: 1;
        .user-name {
          font-size: 18px;
          font-weight: 700;
          color: #2d3a4a;
          margin-bottom: 8px;
          letter-spacing: 0.5px;
          display: flex;
          align-items: center;
          gap: 6px;
          .gender-icon {
            font-size: 18px;
            margin-left: 4px;
            &.male {
              color: #409eff;
            }
            &.female {
              color: #e85e9f;
            }
          }
        }
        .user-location {
          font-size: 14px;
          color: #6b7b8a;
          margin-bottom: 8px;
        }
        .user-status {
          margin-top: 8px;
        }
      }
    }
  }
}
.preset-card-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-height: 320px;
  overflow-y: auto;
  margin: 18px 0 8px 0;
}
.preset-card-item {
  position: relative;
  background: #fafdff;
  border: 1.5px solid #e3eaf6;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.07);
  padding: 20px;
  font-size: 14px;
  color: #2d3a4a;
  cursor: pointer;
  transition: box-shadow 0.18s, border-color 0.18s, background 0.18s;
  display: flex;
  align-items: center;
  min-height: 50px;
  &:hover {
    background: #e6f7ff;
    border-color: #409eff;
    box-shadow: 0 4px 16px rgba(64, 158, 255, 0.13);
    z-index: 2;
  }
  &.is-selected {
    border-color: #409eff;
    background: linear-gradient(90deg, #409eff 10%, #e6f7ff 100%);
    box-shadow: 0 2px 12px rgba(64, 158, 255, 0.18);
    color: #1677ff;
    font-weight: 600;
    .selected-icon {
      color: #52c41a;
      font-size: 18px;
      position: absolute;
      right: 16px;
      top: 50%;
      transform: translateY(-50%);
      font-weight: bold;
    }
  }
  .msg-content {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    white-space: normal;
    transition: color 0.2s, -webkit-line-clamp 0.2s;
    &.expanded {
      // -webkit-line-clamp: unset;
      max-height: none;
    }
  }
  .copy-btn {
    position: absolute;
    right: 36px;
    top: 50%;
    transform: translateY(-50%);
    font-size: 13px;
    color: #409eff;
    opacity: 0.7;
    transition: opacity 0.2s;
    &:hover {
      opacity: 1;
    }
  }
}
.no-preset-messages-card {
  color: #b0b8c9;
  text-align: center;
  padding: 32px 0;
  font-size: 15px;
}
.selected-preset-msg {
  margin-left: 12px;
  color: #409eff;
  font-size: 14px;
  vertical-align: middle;
}
.preset-dialog-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
.preset-dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 0;
}
</style> 